<template>
  <div class="course-management">
    <!-- 主要内容区域 - 添加水平和垂直滚动容器，包裹整个页面内容 -->
    <div class="main-content-wrapper">
    <el-card>
      <!-- 移除卡片头部标题 -->
      
      <!-- 搜索区域 -->
      <el-form :model="searchForm" class="search-form" label-width="80px">
        <el-row :gutter="20" align="middle">
          <el-col :span="6">
            <el-form-item label="课程名称" inline>
              <el-input v-model="searchForm.name" placeholder="请输入" style="width: 180px;" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="课程学科" inline>
              <el-select v-model="searchForm.subject" placeholder="请选择" style="width: 180px;">
                <el-option label="全部" value="" />
                <el-option label="Java" value="1" />
                <el-option label="Python" value="2" />
                <el-option label="前端" value="3" />
                <el-option label="大数据" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="适用人群" inline>
              <el-select v-model="searchForm.target" placeholder="请选择" style="width: 180px;">
                <el-option label="全部" value="" />
                <el-option label="零基础" value="1" />
                <el-option label="中级程序员" value="2" />
                <el-option label="高级开发" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right;">
            <el-form-item>
              <el-button type="primary" @click="handleSearch" style="margin-right: 10px;">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <!-- 操作按钮 - 置于左边 -->
      <div class="action-buttons-left" style="margin-bottom: 20px;">
        <el-button type="primary" @click="handleAdd">+ 添加课程</el-button>
      </div>
      
      <el-table 
        :data="courseList" 
        stripe 
        style="width: 100%; min-width: 1320px; font-size: 14px;"
        :header-cell-style="{ 'font-size': '14px', 'padding': '10px 12px' }"
      >
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column label="课程学科" width="120">
          <template #default="{ row }">
            {{ getSubjectName(row.subject) }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="课程名称" width="180" />
        <el-table-column prop="price" label="价格（元）" width="120" />
        <el-table-column label="适用人群" width="120">
          <template #default="{ row }">
            {{ getTargetName(row.target) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="课程介绍" width="300" />
        <el-table-column prop="updateTime" label="最后更新时间" width="200" />
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <div style="display: flex; gap: 10px; justify-content: center;">
              <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    </div>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleClose"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="课程学科" prop="subject">
          <el-select v-model="formData.subject" placeholder="请选择">
            <el-option label="Java" value="1" />
            <el-option label="Python" value="2" />
            <el-option label="前端" value="3" />
            <el-option label="大数据" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入课程名称" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="适用人群" prop="target">
          <el-select v-model="formData.target" placeholder="请选择">
            <el-option label="零基础" value="1" />
            <el-option label="中级程序员" value="2" />
            <el-option label="高级开发" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程价格" prop="price">
          <el-input v-model.number="formData.price" type="number" placeholder="请输入课程价格" />
        </el-form-item>
        <el-form-item label="课程介绍" prop="description">
          <el-input v-model="formData.description" type="textarea" placeholder="请输入课程介绍，100字以内" maxlength="100" show-word-limit rows="3" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  name: '',
  subject: '',
  target: ''
})

// 课程列表数据
const courseList = ref([])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)

// 表单数据
const formData = reactive({
  id: '',
  subject: '',
  name: '',
  price: '',
  target: '',
  description: ''
})

// 表单验证规则
const formRules = reactive({
  subject: [
    { required: true, message: '请选择课程学科', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 1, max: 50, message: '课程名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入课程价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '课程价格必须大于等于0', trigger: 'blur' }
  ],
  target: [
    { required: true, message: '请选择适用人群', trigger: 'change' }
  ]
})

// 获取课程列表
const getCourseList = async () => {
  try {
    const params = {
      ...searchForm,
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    
    const response = await axios.get('/api/courses', {
      params: params
    })
    
    const result = response.data
    
    if (result && typeof result === 'object') {
      if (result.code === 1) {
        if (result.data && Array.isArray(result.data.rows)) {
          courseList.value = result.data.rows
          pagination.total = Number(result.data.total) || 0
          
          if (courseList.value.length === 0) {
            ElMessage.info('暂无数据')
          }
        } else {
          ElMessage.error('响应数据格式错误')
        }
      } else {
        ElMessage.error(result.msg || '获取课程列表失败')
      }
    } else {
      ElMessage.error('获取课程列表失败')
    }
  } catch (error) {
    ElMessage.error('获取课程列表失败')
    console.error('获取课程列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getCourseList()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.subject = ''
  searchForm.target = ''
  pagination.currentPage = 1
  getCourseList()
}

// 重置表单数据
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.id = ''
  formData.subject = ''
  formData.name = ''
  formData.price = ''
  formData.target = ''
  formData.description = ''
}

// 添加课程
const handleAdd = () => {
  dialogTitle.value = '添加课程'
  resetForm()
  dialogVisible.value = true
}

// 编辑课程
const handleEdit = async (row) => {
  dialogTitle.value = '修改课程'
  resetForm()
  
  try {
    // 根据ID查询课程详情
    const response = await axios.get(`/api/courses/${row.id}`)
    const result = response.data
    
    if (result.code === 1 && result.data) {
      // 填充表单数据
      formData.id = result.data.id
      formData.subject = String(result.data.subject)
      formData.name = result.data.name
      formData.price = result.data.price
      formData.target = String(result.data.target)
      formData.description = result.data.description || ''
      
      dialogVisible.value = true
    } else {
      ElMessage.error(result.msg || '获取课程详情失败')
    }
  } catch (error) {
    ElMessage.error('获取课程详情失败')
    console.error('获取课程详情失败:', error)
  }
}

// 删除课程
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '您确认要删除该课程信息吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await axios.delete(`/api/courses/${row.id}`)
    const result = response.data
    
    if (result.code === 1) {
      ElMessage.success('删除成功')
      getCourseList()
    } else {
      ElMessage.error(result.msg || '删除失败')
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除课程失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    const submitData = {
      ...formData,
      subject: Number(formData.subject),
      target: Number(formData.target)
    }
    
    let response
    if (formData.id) {
      // 修改课程
      response = await axios.put('/api/courses', submitData)
    } else {
      // 添加课程
      response = await axios.post('/api/courses', submitData)
    }
    
    const result = response.data
    
    if (result.code === 1) {
      ElMessage.success(formData.id ? '修改成功' : '添加成功')
      dialogVisible.value = false
      getCourseList()
    } else {
      ElMessage.error(result.msg || (formData.id ? '修改失败' : '添加失败'))
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(formData.id ? '修改失败' : '添加失败')
      console.error('提交表单失败:', error)
    }
  }
}

// 关闭对话框
const handleClose = () => {
  resetForm()
}

// 分页相关处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  getCourseList()
}

const handleCurrentChange = (current) => {
  pagination.currentPage = current
  getCourseList()
}

// 获取学科名称
const getSubjectName = (subject) => {
  const subjectMap = {
    1: 'Java',
    2: 'Python',
    3: '前端',
    4: '大数据'
  }
  return subjectMap[subject] || ''
}

// 获取适用人群名称
const getTargetName = (target) => {
  const targetMap = {
    1: '零基础',
    2: '中级程序员',
    3: '高级开发'
  }
  return targetMap[target] || ''
}

// 组件挂载时加载数据
onMounted(() => {
  getCourseList()
})
</script>

<style scoped>
/* 主内容滚动容器 - 服务于整个页面内容 */
.main-content-wrapper {
  overflow-x: auto; /* 优先启用水平滚动 */
  overflow-y: auto; /* 同时启用垂直滚动 */
  max-height: calc(100vh - 100px); /* 根据页面高度动态调整，确保足够空间 */
  position: relative;
  min-height: 600px;
  padding: 0 15px;
  white-space: nowrap; /* 防止内容换行 */
}

/* 确保卡片元素在滚动容器中正确显示 */
.main-content-wrapper > .el-card {
  min-width: 1320px; /* 最小宽度，确保表格内容不被压缩 */
  width: 100%;
  box-sizing: border-box;
  white-space: normal; /* 允许卡片内部内容正常换行 */
}

/* 自定义滚动条样式 */
.main-content-wrapper::-webkit-scrollbar {
  height: 6px;
  width: 6px;
}

.main-content-wrapper::-webkit-scrollbar-track {
  background: #f0f0f0;
  border-radius: 3px;
}

.main-content-wrapper::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
  transition: background-color 0.3s;
}

.main-content-wrapper::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

/* 兼容其他浏览器 */
.main-content-wrapper {
  scrollbar-width: thin;
  scrollbar-color: #c0c4cc #f0f0f0;
}

/* 确保表格内容在滚动时不会溢出 */
:deep(.el-table) {
  min-width: 1320px; /* 确保表格有足够的最小宽度 */
  width: 100%;
  margin-bottom: 0;
}

/* 调整操作按钮样式 */
:deep(.el-button--small) {
  padding: 4px 12px;
  font-size: 12px;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

/* 搜索表单样式 */
.search-form {
  margin-bottom: 20px;
}

/* 操作按钮样式 */
.action-buttons-left {
  margin-bottom: 20px;
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
